<template>
  <div class="app-container eutr-content">
    <div class="eutr-content-left">
      <el-tree
        :data="treeData"
        show-checkbox
        default-expand-all
        node-key="id"
        ref="tree"
        highlight-current
        :props="defaultProps"
        @check="handleCheckChange"
      >
      </el-tree>
    </div>
    <div class="eutr-content-right">
      <div>
        <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
          <el-tab-pane label="多站点单因子（小时）" name="hour">
            <!-- 搜索条件区域 -->
            <div class="search-container">
              <el-form :inline="true" class="demo-form-inline">
                <el-form-item label="监测因子：">
                  <el-select
                    v-model="monitorFactor"
                    placeholder="请选择监测因子"
                    @change="handleQuery"
                  >
                    <el-option
                      v-for="item in bussinessItemList"
                      :key="item.itemCode"
                      :label="item.itemName"
                      :value="item.itemCode"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="时间：">
                  <el-date-picker
                    v-model="dateRange"
                    type="daterange"
                    range-separator="到"
                    @change="handleQuery"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    value-format="yyyy-MM-dd"
                  ></el-date-picker>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="handleQuery"
                    >查询</el-button
                  >
                  <!-- <el-button @click="handleSetYAxis">设置Y轴</el-button>
                                    <el-button @click="handleSetTitle">标题</el-button> -->
                </el-form-item>
              </el-form>
            </div>

            <!-- 图表容器 -->
            <div class="chart-container">
              <div class="chart-title">
                {{ monitorFactorName }} 变化趋势分析图
              </div>
              <div
                id="hourChart"
                ref="hourChart"
                style="width: 100%; height: 400px"
              ></div>
            </div>
          </el-tab-pane>
          <el-tab-pane label="多站点单因子（日）" name="day">
            <!-- 搜索条件区域 -->
            <div class="search-container">
              <el-form :inline="true" class="demo-form-inline">
                <el-form-item label="监测因子：">
                  <el-select
                    v-model="monitorFactor"
                    placeholder="请选择监测因子"
                    @change="handleQuery"
                  >
                    <el-option
                      v-for="item in bussinessItemList"
                      :key="item.itemCode"
                      :label="item.itemName"
                      :value="item.itemCode"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="时间：">
                  <el-date-picker
                    v-model="dateRange"
                    type="daterange"
                    range-separator="到"
                    @change="handleQuery"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    value-format="yyyy-MM-dd"
                  ></el-date-picker>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="handleQuery"
                    >查询</el-button
                  >
                </el-form-item>
              </el-form>
            </div>

            <!-- 图表容器 -->
            <div class="chart-container">
              <div class="chart-title">
                {{ monitorFactorName }}变化趋势分析图
              </div>
              <div
                id="dayChart"
                ref="dayChart"
                style="width: 100%; height: 400px"
              ></div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
  </div>
</template>
<script>
import { segmentRegionTree } from "@/api/dataResources/waterJcData/sgMonitor.js";
import { getMultiSectionSingleFactor } from "@/api/riverGeneralMange/riverGeneralMange.js";
import { bussinessItemData } from "@/api/dataResources/waterJcData/sgMonitor";
import * as echarts from "echarts";
export default {
  data() {
    return {
      isFirstLoad: true,
      treeData: [],
      activeName: "hour",
      defaultProps: {
        children: "children",
        label: "label",
      },
      // 监测因子相关数据
      monitorFactor: "",
      monitorFactorName: "",
      // 日期范围
      dateRange: [],
      // ECharts实例
      chartInstances: {
        hour: null,
        day: null,
      },
      // 选中的节点数据
      selectedNodes: [],
      bussinessItemList: [],
      // 从API获取的图表数据
      chartApiData: null,
    };
  },
  watch: {
    monitorFactor: {
      handler(val) {
        this.monitorFactorName = this.bussinessItemList.find(
          (item) => item.itemCode == val
        )?.itemName;
      },
    },
    activeName(newVal, oldVal) {
      // 选项卡切换时，优化初始化逻辑
      if (!this.chartInstances[newVal]) {
        // 延迟初始化，确保容器已经显示
        setTimeout(() => {
          this.initChart(newVal);
        }, 50);
      } else {
        // 如果图表已初始化，先调整尺寸
        setTimeout(() => {
          if (this.chartInstances[newVal]) {
            this.chartInstances[newVal].resize();
          }
        }, 50);
      }
    },
  },
  created() {
    // this.query()
    // this.createdFn()
  },
  mounted() {
    this.createdFn();
  },

  beforeDestroy() {
    // 组件销毁前销毁所有图表实例
    Object.keys(this.chartInstances).forEach((key) => {
      if (this.chartInstances[key]) {
        this.chartInstances[key].dispose();
      }
    });
  },
  methods: {
    async createdFn() {
      const endDate = $moment().format("{yyyy}-{mm}-{dd}");
      const startDate = $moment()
        .offset("month", -1)
        .format("{yyyy}-{mm}-{dd}");
      this.dateRange = [startDate, endDate];
      await this.getRegonTree();
      await this.getBussinessItemData();
      await this.getMultiSectionSingleFactor();
    },
    async getBussinessItemData() {
      try {
        const res = await bussinessItemData({ bussinessCategoryCode: "Auto" });
        if (res.code == 200) {
          this.bussinessItemList = res.data;
          // 如果业务项列表不为空，默认选择第一项
          if (this.bussinessItemList && this.bussinessItemList.length > 0) {
            this.monitorFactor = this.bussinessItemList[0].itemCode;
          }
        }
      } catch (error) {
        console.error("Error fetching business items:", error);
      }
    },
    async getMultiSectionSingleFactor() {
      await this.updateActiveChartData();
      const params = {
        segmentid: this.selectedNodes.map((item) => item.id).join(","),
        itemcode: this.monitorFactor,
        startTime: this.dateRange[0],
        endTime: this.dateRange[1],
        datatype: this.activeName == "hour" ? 0 : 1,
      };
      let res = await getMultiSectionSingleFactor(params);
      if (res.code == 200) {
        // this.chartApiData = res.data;
        let resData = res.data;
        let timeData = [],
          seriesData = [];
        for (let resitem of resData) {
          let time =
            this.activeName == "hour"
              ? this.parseTime(resitem.sampletime, "{yyyy}-{mm}-{dd} {hh}:{ii}")
              : this.parseTime(resitem.sampletime, "{yyyy}-{mm}-{dd}");
          timeData.push(time);
          if (seriesData.length == 0) {
            let item = {
              name: resitem.segmentname,
              type: "line",
              emphasis: { focus: "series" },
              data: [],
            };
            item.data.push(resitem.effectivevalue);
            seriesData.push(item);
          } else {
            let item = seriesData.find(
              (item) => item.name == resitem.segmentname
            );
            if (item) {
              item.data.push(resitem.effectivevalue);
            } else {
              item = {
                name: resitem.segmentname,
                type: "line",
                emphasis: { focus: "series" },
                data: [],
              };
              item.data.push(resitem.effectivevalue);
              seriesData.push(item);
            }
          }
        }
        this.chartApiData = { timeData, seriesData };
        // 更新图表数据
        this.updateChartWithApiData();
      }
    },
    // 处理树节点勾选事件
    handleCheckChange(data, checkedInfo) {
      // 获取所有选中的节点
      this.selectedNodes = this.$refs.tree.getCheckedNodes(true);
      // 只保留二级节点（叶子节点）
      this.selectedNodes = this.selectedNodes.filter(
        (node) => !node.children || node.children.length === 0
      );
      // 更新当前激活的图表
      this.getMultiSectionSingleFactor();
    },
    async getRegonTree() {
      try {
        const res = await segmentRegionTree({
          segmentType: "IsAuto",
          segmentTypeDrink: "filter",
        });
        if (res.code == 200) {
          this.treeData = this.convertToTree(res.data || []);

          // 延迟执行，确保DOM已经渲染
          await this.delefn(100);
          // 遍历所有节点，找出所有叶子节点（没有children或children为空的节点）
          const findAllLeafNodes = (nodes) => {
            let leafNodes = [];
            nodes.forEach((node) => {
              if (!node.children || node.children.length === 0) {
                leafNodes.push(node);
              } else {
                leafNodes = leafNodes.concat(findAllLeafNodes(node.children));
              }
            });
            return leafNodes;
          };

          // 获取所有叶子节点
          const leafNodes = findAllLeafNodes(this.treeData);

          // 默认选中所有叶子节点
          if (this.$refs.tree && leafNodes.length > 0) {
            this.$refs.tree.setCheckedNodes(leafNodes);
            // 更新selectedNodes
            this.selectedNodes = leafNodes;
          }
        }
      } catch (error) {
        console.error("获取区域树数据失败:", error);
        this.$message.error("获取区域树数据失败，请稍后重试");
      }
    },

    convertToTree(list) {
      // 创建一个映射表，用于快速查找节点
      const map = {};
      const treeData = [];

      // 初始化所有节点
      list.forEach((item) => {
        map[item.id] = {
          id: item.id,
          label: item.name,
          ...item,
          children: [],
        };
      });

      // 构建树形结构
      list.forEach((item) => {
        const node = map[item.id];
        if (item.pId === "0" || !item.pId) {
          // 根节点
          treeData.push(node);
        } else {
          // 子节点
          const parent = map[item.pId];
          if (parent) {
            parent.children.push(node);
          } else {
            // 如果找不到父节点，则作为根节点处理
            treeData.push(node);
          }
        }
      });

      return treeData;
    },

    handleClick(tab, event) {
      this.getMultiSectionSingleFactor();
      // // 切换选项卡时，确保当前选项卡的图表已初始化和正确渲染
      // if (!this.chartInstances[tab.name]) {
      //     // 延迟初始化，确保容器已经显示
      //     setTimeout(() => {
      //         this.initChart(tab.name);
      //         setTimeout(() => {
      //             this.getMultiSectionSingleFactor();
      //         }, 100);
      //     }, 50);
      // } else {
      //     // 如果图表已初始化，则先调整尺寸再更新数据
      //     setTimeout(() => {
      //         if (this.chartInstances[tab.name]) {
      //             this.chartInstances[tab.name].resize();
      //             this.getMultiSectionSingleFactor();
      //         }
      //     }, 50);
      // }
    },

    // 初始化图表
    initChart(chartType) {
      // 获取对应的图表容器
      const chartDom =
        chartType === "hour" ? this.$refs.hourChart : this.$refs.dayChart;
      if (!chartDom) return;

      // 如果已有图表实例，先销毁
      if (this.chartInstances[chartType]) {
        this.chartInstances[chartType].dispose();
      }

      // 创建ECharts实例
      this.chartInstances[chartType] = echarts.init(chartDom);

      // 设置图表配置项
      const option = this.getChartOption();
      this.chartInstances[chartType].setOption(option);

      // 强制重新计算尺寸，确保正确渲染
      setTimeout(() => {
        if (this.chartInstances[chartType]) {
          this.chartInstances[chartType].resize();
        }
      }, 100);

      // 添加窗口大小变化时的图表自适应
      window.addEventListener("resize", () => {
        if (this.chartInstances[chartType]) {
          this.chartInstances[chartType].resize();
        }
      });
    },

    // 更新当前激活的图表数据
    async updateActiveChartData() {
      if (this.chartInstances[this.activeName]) {
        // 先更新图表配置中的yAxis名称
        this.chartInstances[this.activeName].setOption({
          yAxis: {
            name: this.monitorFactorName,
          },
        });
      } else {
        this.initChart(this.activeName);
        await this.delefn(100);
      }
      this.chartInstances[this.activeName].resize();
    },
    delefn(time) {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve();
        }, time);
      });
    },

    // 获取图表配置项
    getChartOption() {
      // 使用选中的节点名称作为legend的数据源
      const legendData = this.selectedNodes.map((node) => node.label);

      return {
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "cross",
            label: {
              backgroundColor: "#6a7985",
            },
          },
        },
        legend: {
          data: legendData,
          top: 0,
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: true,
        },
        xAxis: [
          {
            type: "category",
            boundaryGap: false,
            data: [],
            name: "时间",
          },
        ],
        yAxis: [
          {
            type: "value",
            name: this.monitorFactorName,
            min: 0,
            max: 8,
          },
        ],
        series: [],
      };
    },

    // 使用API数据更新图表
    updateChartWithApiData() {
      const chartInstance = this.chartInstances[this.activeName];
      if (!chartInstance) return;
      // 先检查API数据是否存在且有效
      if (!this.chartApiData) {
        console.warn("API数据为空，使用模拟数据");
        this.useMockDataForChart();
        return;
      }

      try {
        // 尝试处理API返回的数据
        // 这里我们需要检查API返回的数据结构并相应地处理
        let timeData = [];
        let seriesData = [];

        // 计算y轴的最大值（可以根据实际需求调整）
        let maxYValue = 8; // 默认值

        // 检查chartApiData是否已经包含完整的图表数据结构
        if (this.chartApiData.timeData && this.chartApiData.seriesData) {
          // 标准格式
          timeData = this.chartApiData.timeData;
          seriesData = this.chartApiData.seriesData;

          // 计算所有数据中的最大值，并留出一定余量
          if (seriesData && seriesData.length > 0) {
            const allValues = seriesData.flatMap((item) =>
              item.data
                ? item.data.filter((val) => val !== null && val !== undefined)
                : []
            );
            if (allValues.length > 0) {
              const currentMax = Math.max(...allValues);
              // 设置max值为当前最大值的1.2倍，或保持默认值，取较大者
              maxYValue = currentMax * 1.2;
              // 可以根据需要进行四舍五入
              maxYValue = Math.ceil(maxYValue);
            }
          }
        } else {
          // 假设API返回了一个直接可用于series的数据结构
          // 检查是否有data或其他可能包含时间数据的属性
          console.log("API数据结构检查:", this.chartApiData);

          // 这里添加对不同数据结构的处理逻辑
          // 由于不了解实际API返回格式，我们暂时使用模拟数据
          console.warn("API数据结构不符合预期，使用模拟数据");
          // this.useMockDataForChart();
          return;
        }

        // 确保seriesData是数组格式
        const seriesDataArray = Array.isArray(seriesData)
          ? seriesData
          : seriesData
          ? [seriesData]
          : [];

        // if (timeData.length > 0 && seriesDataArray.length > 0) {
        // 清除图表之前的数据，确保完全替换
        chartInstance.clear();
        // 更新图表数据，使用notMerge确保完全替换现有配置
        chartInstance.setOption({
          // 同时更新legend数据，只包含实际有数据的系列名称
          legend: {
            data: seriesDataArray.map((item) => item.name),
          },
          xAxis: {
            data: timeData,
          },
          yAxis: [
            {
              type: "value",
              name: this.monitorFactorName,
              min: 0,
              max: maxYValue, // 使用计算得到的最大值
            },
          ],
          series: seriesDataArray.map((item) => ({
            name: item.name || "数据系列",
            type: "line",
            emphasis: {
              focus: "series",
            },
            data: item.data || [],
          })),
        });
        // } else {
        //     console.log('数据为空');
        // }
      } catch (error) {
        console.error("处理API数据时出错:", error);
        // this.useMockDataForChart();
      }
    },

    // 查询按钮点击事件
    handleQuery() {
      // 调用加载数据的方法
      this.getMultiSectionSingleFactor();
    },

    // 设置Y轴按钮点击事件
    handleSetYAxis() {
      this.$prompt("请输入Y轴最大值", "设置Y轴", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputPattern: /^[0-9]+(\.[0-9]+)?$/,
        inputErrorMessage: "请输入有效的数字",
      })
        .then(({ value }) => {
          const maxValue = parseFloat(value);
          if (this.chartInstance && !isNaN(maxValue)) {
            this.chartInstance.setOption({
              yAxis: {
                max: maxValue,
              },
            });
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消设置",
          });
        });
    },

    // 标题按钮点击事件
    handleSetTitle() {
      this.$prompt("请输入图表标题", "设置标题", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      })
        .then(({ value }) => {
          if (value && value.trim()) {
            // 更新图表标题
            const titleElement = document.querySelector(".chart-title");
            if (titleElement) {
              titleElement.textContent = value.trim();
            }
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消设置",
          });
        });
    },
  },
};
</script>
<style scoped>
.eutr-content {
  display: flex;
}

/* .eutr-content-left {
    width: 20%;
    height: 100%;
    background-color: #fff;
    padding: 20px;
    box-sizing: border-box;
    border-right: 1px solid #e4e7ed;
}

.eutr-content-right {
    width: 80%;
    height: 100%;
    background-color: #fff;
    padding: 20px;
    box-sizing: border-box;
} */

/* 搜索区域样式 */
.search-container {
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.demo-form-inline {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}

.demo-form-inline .el-form-item {
  margin-right: 15px;
  margin-bottom: 10px;
}

.selected-count {
  background-color: #e6f7ff;
  color: #1890ff;
  padding: 4px 12px;
  border-radius: 10px;
  font-size: 14px;
}

/* 图表区域样式 */
.chart-container {
  background-color: #fff;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 15px;
}

.chart-title {
  font-size: 16px;
  font-weight: bold;
  text-align: center;
  margin-bottom: 15px;
  color: #303133;
}

/* 选项卡样式调整 */
.el-tabs__content {
  padding-top: 15px;
}

/* 响应式布局 */
@media (max-width: 1200px) {
  .demo-form-inline {
    flex-direction: column;
    align-items: stretch;
  }

  .demo-form-inline .el-form-item {
    margin-right: 0;
  }
}

.eutr-content-left {
  width: 300px;
  height: 100%;
  background-color: #fff;
  padding: 20px;
  box-sizing: border-box;
}

.eutr-content {
  display: flex;
  justify-content: space-around;
}

.eutr-content-right {
  width: calc(100% - 320px);
  background-color: #fff;
  padding: 20px;
  box-sizing: border-box;
  height: 100%;
}
</style>
